<template>
    <div class="calendar_box">
        <el-row :gutter="20">
            <el-col :span="18">
                <full-calendar ref="fullCalendar" style="height: 100%" :options="calendarOptions"></full-calendar>
            </el-col>
            <!--<el-col :span="6" class="detail_box">
                <div class="addbtn">
                    <el-button type="primary"  size="small">添加排班</el-button>
                </div>
                <el-alert title="排班信息" type="success" :closable="false"> </el-alert>
                <el-form :model="form" label-width="100px">
                    <el-form-item label="排班标题：" >
                        {{form.title}}
                    </el-form-item>
                    <el-form-item label="科室：" >
                        {{form.ksName}}
                    </el-form-item>
                    <el-form-item label="出诊医生：" >
                        {{form.doctorName}}
                    </el-form-item>
                    <el-form-item label="联系电话：" >
                        {{form.phone}}
                    </el-form-item>
                    <el-form-item label="出诊时间：" >
                        {{form.ctime}}
                    </el-form-item>
                    <div class="addbtn" style="text-align: right;margin-right: 20px;">
                        <el-button type="primary"  size="small" v-show="isShowBtn">修改</el-button>
                        <el-button type="danger" size="small" v-show="isShowBtn">删除</el-button>
                    </div>
                </el-form>
            </el-col> -->
        </el-row>  
        
             <!-- 添加或修改 -->
        <el-dialog title="编辑排班" :visible.sync="dialogFormVisible" width="40%">
            <el-form :model="form" label-width="150px">
                <el-form-item label="日期" >
                    <el-input v-model="form.date"  placeholder="" autocomplete="off" readonly></el-input>
                </el-form-item>
                <el-form-item label="排班类型" >
                     <el-select v-model="form.workType" placeholder="请选择排班类型" @change="onWorkTypeChange">
                        <el-option
                            v-for="item in form.workTypeList"
                            :key="item.workType"
                            :label="item.text"
                            :value="item.workType"
                            >
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- 可预约时间段选择 -->
                <el-form-item label="可预约时间段" v-if="form.workType > 0">
                <div class="time_div">
                    <div v-for="item in getAvailableTimeSlots" 
                        :key="item.showTime" 
                        :class="{
                        'time-disabled': item.yy_time !== 0,
                        'time-available': item.kk_time === 1 && item.yy_time === 0,
                        }"
                        @click="handleAppointmentClick(item)">
                    {{item.showTime}}
                    <br>{{ item.yy_time !== 0 ? '已被预约' : '' }}
                    </div>
                </div>
                </el-form-item>

                <!-- 可重复预约时间段选择 -->
                <el-form-item label="可重复预约时间段" v-if="form.workType > 0">
                <div class="time_div">
                    <div v-for="item in getAvailableTimeSlots" 
                        :key="item.showTime" 
                        :class="{
                        'time-disabled': item.yy_time === 2,
                        'time-repeat-available': item.dd_time === 1 && item.yy_time !== 2,
                        }"
                        @click="handleRepeatClick(item)">
                        {{item.showTime}}
                    <br>{{ item.yy_time == 2 ? '已被重复预约' : '' }}
                    </div>
                </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="saveSchedule">保存</el-button>
            </div>
        </el-dialog>

   </div>
</template>

<script>
import { scheduleList , setSchedule,getShopBusinessTime } from "@/api/staff";
import FullCalendar from "@fullcalendar/vue";
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";
import axios from 'axios'
 export default {
    name:'FindPaiban',
    components:{FullCalendar},
    data() {
        return {
            staffId:'',
            shopId:'',
            isShowBtn: false,
            dialogFormVisible:false,
            amList: [],
            pmList: [],
            full_dayList: [],
            appointTime:[], // 点击可预约时间段
            repeatTime:[],// 点击可重复预约时间段
           form:{
                //workTypeList:new Date(),
                id:"",
                date:"",
                shopId:'',
                workType:'',
                className:"",
                workTypeList:[
                    {
                        workType:0,
                        text:"休"
                    },
                    {
                        workType:1,
                        text:"全天班"
                    },
                    {
                        workType:2,
                        text:"上午班"
                    },
                    {
                        workType:3,
                        text:"下午班"
                    }
                ],
            },
            formLabelWidth:120,
            calendarOptions: {
                    //   timeGridPlugin  可显示每日时间段
                    height: 600,
                    plugins: [dayGridPlugin, interactionPlugin],
                    headerToolbar: {
                    left: "prev",
                    center: "title",
                    right: "next",
                    // right: 'agendaWeek,dayGridWeek,dayGrid'
                },
                buttonText: {
                    // 设置按钮
                    today: "今天",
                    month: "月",
                    week: "周",
                    dayGrid: "天",
                },
                // allDaySlot: false,
                editable: true,
                selectable: true,
                navLinks: true,
                // displayEventEnd: true,//所有视图显示结束时间
                initialView: "dayGridMonth", // 设置默认显示月，可选周、日
                //dateClick: this.handleEventClick,
                eventClick: this.handleEventClick,
                eventsSet: this.handleEvents,
                select: this.handleDateSelect,
                // timezone
                // 设置日程
                events: [],
                //events格式如下
                 // {
		          // 	id: 1,
		          // 	title: '09:30~11:30 小破孩',
		          // 	start: '2020-12-11',
		          // 	end: '2020-12-13',
		          // 	color: '#f08f00',
		          // },
		          // {
		          // 	id: 2,
		          // 	title: '9:30~14:30 项目会议',
		          // 	start: '2020-12-14',
		          // 	end: '2020-12-14',
		          // 	color: '#6bb377',

                eventColor: "#f08f00", // 修改日程背景色
                locale: "zh-cn", // 设置语言
                weekNumberCalculation: "ISO", // 周数
                customButtons: {}
            },
            doctorList:[]
        };
    },
      computed: {
        getAvailableTimeSlots() {
            switch (this.form.workType) {
                case 1: // 全天班
                return this.full_dayList;
                case 2: // 上午班
                return this.amList;
                case 3: // 下午班
                return this.pmList;
                default:
                return [];
            }
        },
    },
    mounted(){
        this.getPaiban();
        //this.getAllDoctor()
    },
    methods: {
        //获取排班
        getPaiban(){
            //console.log(this.id);
            scheduleList({ staffIds: [this.$route.query.id] }).then((res) => {
                //console.log(res.data.data);
                //this.list = res.data.data;
                this.name = res.data.data.name;
                this.staffId = this.$route.query.id;
                this.shopId = this.$route.query.shop_id
                //this.year = res.data.data.year;
                //res.data.data.splice('id',1);
                //res.data.data.splice('id',1);
                //res.data.data.splice('year',1);
                var result = new Array();
                //result = res.data.data[0];
                //console.log(result);
                Object.keys(res.data.data[0]).forEach(function (key) {
                    if(key != "id" && key != "name" && key != "year")
                        {
                            var arr = new Array();
                            arr.start=res.data.data[0]['year']+'-'+key;
                            //console.log(res.data.data[0][key]);
                            switch(res.data.data[0][key]){
                                case 0:{
                                
                                    arr.textColor = 'white';
                                    arr.color = 'ForestGreen';
                                    arr.title = "休";
                                    arr.className = "eventone";
                                    break;
                                }
                                case 1:{
                    
                                    arr.textColor = '#6b849d';
                                    arr.color = '#dfe2e9';
                                    arr.title = "全天班";
                                    arr.className = "eventone";
                                    break;
                                }
                                case 2:{
                                    arr.textColor = 'white';
                                    arr.color = '#2bada8';
                                    arr.title = "上午班";
                                    break;
                                }
                                case 3:{
                      
                                    arr.textColor = 'white';
                                    arr.color = '#c96bc2';
                                    arr.title = "下午班";
                                    break;
                                }
                            }
                            result.push(arr);
                            //arr.doctorName = d.doctorName;
                            //arr.ksName = d.ksName;
                            //arr.phone = d.phone;
                            //res.data.data[0][key]
                        }

                });

                this.calendarOptions.events=result;
            })
            
        },
        //保存
        //点击排班事件
       async handleEventClick(calEvent){
            this.isShowBtn = true;
            this.form.date = calEvent.event.startStr.replace(/-/g, ''),
            console.log(calEvent.event);
            await getShopBusinessTime({shop_id: this.$route.query.shop_id, shop_person_id: this.$route.query.id, time: this.form.date}).then((res) => {
                this.amList = res.data.am;
                this.pmList = res.data.pm;
                this.full_dayList = res.data.day;
                this.appointTime = [];
                this.repeatTime = [];
                switch(calEvent.event.title){
                    case "全天班":{
                        this.form.workType = 1;
                        break;
                    }
                    case "上午班":{
                        this.form.workType = 2;
                        break;
                    }
                    case "下午班":{
                        this.form.workType = 3;
                        break;
                    }
                    case "休":{
                        this.form.workType = 0;
                        break;
                    }
                }
                this.onWorkTypeChange(this.form.workType);
            })
      
            this.dialogFormVisible = true
                
         

            this.form.id = this.$route.query.id;
        },
        saveSchedule(){

          
            let params = {
                    shop_id:this.$route.query.shop_id,
                    time:this.form.date,
                    shop_person_id:this.form.id,
                    work_type:this.form.workType == 0 || this.form.workType == 1?'0':(this.form.workType-1),
                    is_work:this.form.workType == 0 ?'0':'1',
                    kk_time:this.appointTime,
                    dd_time:this.repeatTime
                }
                setSchedule(params).then((res) => {
                    if(res.code != 200){
                        this.$message({
                            message: res.msg,
                            type: 'warning'
                        });
                    }else{
                        this.$message({
                            message: res.data.msg,
                            type: 'success'
                        });
                    }
                    this.getPaiban();
                })
            this.dialogFormVisible = false;
        },
        
                // 处理可预约时间段点击
            handleAppointmentClick(item) {
            // 如果时段不可预约，不执行任何操作
                if (item.yy_time !== 0) return;
                const timeKey = item.showTime;
                if(item.kk_time === 1){
                    item.kk_time = 0;
                    this.appointTime = this.appointTime.filter(
                        time => time !== timeKey
                        );
                }else if(item.kk_time === 0){
                    item.kk_time = 1;
                    this.appointTime.push(item.showTime)
                }
            },
            
            // 处理可重复预约时间段点击
            handleRepeatClick(item) {
            // 如果时段不可重复预约，不执行任何操作
                if (item.yy_time === 2) return;
                const timeKey = item.showTime;
                if(item.dd_time === 1){
                    item.dd_time = 0;
                    this.repeatTime = this.repeatTime.filter(
                        time => time.showTime !== timeKey
                    );

                }else if(item.dd_time === 0){
                    item.dd_time = 1;
                    this.repeatTime.push(item.showTime)
                }
            },
         // 排班类型变更时
            onWorkTypeChange(e) {
                this.appointTime = [];
                this.repeatTime = [];
                if(e == 1){
                    this.appointTime = this.full_dayList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => (item.showTime));
                    this.repeatTime = this.full_dayList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => ( item.showTime));
                }else if(e == 2 ){
                    this.appointTime = this.amList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => (item.showTime));
                    this.repeatTime = this.amList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => ( item.showTime));
                }else if(e == 3){
                    this.appointTime = this.pmList.filter(item => item.kk_time === 1 && item.yy_time === 0).map(item => ( item.showTime));
                    this.repeatTime = this.pmList.filter(item => item.dd_time === 1 && item.yy_time !== 2).map(item => (item.showTime));
                }
            
            },
    }
}
</script>


<style scoped lang="scss">
::v-deep .el-input{
    width: 200px!important;
}
.time_div {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 8px 0;
  
  div {
    padding: 0 12px;
    border-radius: 4px;
    text-align: center;
    // min-width: 80px;
    transition: all 0.2s;
    cursor: pointer;
    border: 1px solid #EBEEF5;
  }
  
  .time-disabled {
    background-color: #909399;
    color: #fff;
    cursor: not-allowed;
  }
  
  .time-available {
    background-color: #33bea7;
    border: 1px solid #33bea7;
    color: #fff;
    &:hover {
      border-color: #33bea7;
    }
  }
  
  .time-selected {
    background-color: #33bea7;
    color: #fff;
    border-color: #33bea7;
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .time-repeat-available {
    // background-color: #fff;
    // border: 1px solid #EBEEF5;
    background-color: #33bea7;
    border: 1px solid #33bea7;
    color: #fff;
    &:hover {
      border-color: #2bada8;
    }
  }
  
  .time-repeat-selected {
    background-color: #2bada8;
    color: #fff;
    border-color: #2bada8;
    transform: translateY(-2px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
}

.addbtn{
    margin-top:15px;
    text-align: left;
    margin-bottom:15px;
}
.calendar_box>>>.el-dialog{
    width: 450px;
}
.calendar_box>>>.el-date-editor.el-input{
    width: 330px;
}
.el-select{
    width: 100%;
}
.detail_box>>>.el-form{
    border:1px solid #ddd;
}
.detail_box>>>.el-form-item__content{
    text-align: left;
    color: #333;
}
.eventone{
    color: #333;
}
</style>


